/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.compomics.fastagenerator.fastagrabber.consoleformatter;

import java.io.Console;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Kenneth
 */
public class Spinner {

    private Console console;
    private boolean spinning = false;
    private static String[] spinner = new String[]{"/", "-", "\\", "|"};
    private Thread spinningThread;
    private String prefix = "";
    private String suffix = "";

    public Spinner() throws Exception {
        console = System.console();
        if (console == null) {
            throw new Exception("No formatter found for console interface...");
        } else {
            System.out.println("");
            console.printf("");
        }
    }

    public Spinner(String prefix) {
        this.prefix = prefix;
    }

    public Spinner(String prefix, String suffix) {
        this.prefix = prefix;
        this.suffix = suffix;
    }

    public void startSpinner() throws InterruptedException {
        if (console != null) {
            spinningThread = new Thread(new Runnable() {
                @Override
                public void run() {
                    spinning = true;
                    console.printf("|");
                    while (spinning) {
                        for (int i = 0; i < spinner.length; i++) {
                            try {
                                Thread.sleep(150);
                            } catch (InterruptedException ex) {
                            }
                            clearTotal();
                            console.printf(spinner[i]);
                            console.printf(suffix);
                        }
                    }
                }
            });
            spinningThread.start();
        }
    }

    private void clearTotal() {
        if (console != null) {
            for (int i = 0; i <= spinner[i].length(); i++) {
                console.printf("\u0008");
            }
        }
    }

    public void stopSpinner(boolean newLine) {
        if (console != null) {
            console.printf("\u0008");
            console.printf("\u0008");
            spinning = false;
            spinningThread.interrupt();
            if (newLine) {
                console.printf("\n");
            }
            try {
                Thread.sleep(500);
                console.printf("\u0008");
            } catch (InterruptedException ex) {
            }
        }
    }
}
